<?php

namespace app\api\controller;

use think\Controller;
use think\Request;

class Common extends Controller
{
    var $uinfo;
    var $postData;
    var $token;

    public function _initialize()
    {
        $this->postData = Request::instance()->param();
        $noLoginAction = ['vipintro/intro', 'article/articlelist', 'adminuser/get_reginfo', 'adminuser/login', 'member/add', 'adminuser/register', 'pay/alipay_return', 'article/articledetail', 'redpacket/checkredpacket', 'redpacket/createredpacket'];
        $nowurl = $this->postData['controller'] . "/" . $this->postData['action'];

        /* 读取数据库中的配置 */
        $config = cache('DB_CONFIG_DATA');
        if (!$config) {
            $config = model('Config')->lists();
            cache('DB_CONFIG_DATA', $config);
        }
        config($config); //添加配置

        $user_agent = Request::instance()->header("user-agent");
        if (strpos($user_agent, "Coco3gAppAndroid") !== false) {
            define("DEVICE", "android");
        } elseif (strpos($user_agent, "Coco3gAppIOS") !== false) {
            define("DEVICE", "ios");
        } else {
            define("DEVICE", "mobile");
        }

        if (!in_array(strtolower($this->postData['controller']), ['index', 'pay', 'accessory']) && !in_array($nowurl, $noLoginAction)) {
            if ($this->check_auth() === false) {
                return $this->app_error('请登录', 201);
            }
        }
        unset($this->postData['controller']);
        unset($this->postData['action']);
    }

    protected function set_str_type($data)
    {
        $data = json_decode(json_encode($data), true);
        $datas = [];
        foreach ($data as $k => $v) {
            if (is_array($v)) {
                $datas[$k] = $this->set_str_type($v);
            } else {
                $datas[$k] = strval($v);
            }
        }
        return $datas;
    }

    protected function check_auth()
    {
        $token = Request::instance()->header('token');
        $timestamp = Request::instance()->header('timestamp');
        $uinfo = model("MemberToken")->check_token($token, $timestamp);
        // $uinfo = model('AdminUser')->get_data(['item_id'=>7]);
        if (!empty($uinfo)) {
            $this->uinfo = $uinfo;
            $this->token = $token;
        } else {
            model("MemberToken")->delete_token($token);
            return false;
        }
        return true;
    }

    protected function app_success($data = [], $message = '', $code = 200, $other = [])
    {
        header("HTTP/1.1 200 OK");
        header("Content-Type:application/json; charset=utf-8");
        $data = $data ? $this->set_str_type($data) : [];
        $result = [
            'code' => $code,
            'msg' => $message,
            'response' => $data,
            'request' => $this->postData,
            'other' => $this->set_str_type($other),
        ];
        echo json_encode($result);
        exit();
    }

    protected function app_error($message = '', $code = 400, $data = [])
    {
        header("HTTP/1.1 400 Bad Request");
        header("Content-Type:application/json; charset=utf-8");
        $data = $this->set_str_type($data);
        $result = [
            'code' => $code,
            'msg' => $message,
            'response' => $this->set_str_type($data),
            'request' => $this->postData,
            'other' => [],
        ];
        echo json_encode($result);
        exit();
    }

    public function add()
    {
        $id = $this->modelDb->save_data($this->postData);
        if ($id === false) {
            return $this->app_error($this->modelDb->getError());
        } else {
            $info = $this->modelDb->get_data(['item_id' => $id]);
        }
        return $this->app_success($info);
    }

    public function update()
    {
        $id = $this->modelDb->update_data($this->postData);
        if ($id === false) {
            return $this->app_error($this->modelDb->getError());
        }
        // else{
        //     $info = $this->modelDb->get_data($id);
        // }
        return $this->app_success();
    }

    public function delete()
    {
        $id = $this->modelDb->delete_data($this->postData);
        if ($id) {
            return $this->app_success();
        } else {
            return $this->app_error("删除失败");
        }
    }

    public function detail()
    {
        $info = $this->modelDb->get_data($this->postData);
        return $this->app_success($info);
    }

    public function index()
    {
        $data = $this->modelDb->list_data($this->postData);
        if ($data) {
            return $this->app_success($data);
        } else {
            return $this->app_error("获取失败");
        }
    }

    public function upload(Request $request)
    {
        // 获取表单上传文件
        $file = $request->file('Filedata');
        if (empty($file)) {
            return $this->app_error("请选择上传文件");
        }
        // 移动到框架应用根目录/public/uploads/ 目录下
        $info = $file->validate(['size' => 1024 * 1024 * 1024, 'ext' => 'jpg,png,gif,mp4,jpeg'])->move(ROOT_PATH . 'upload' . DS);
        $getSaveName = str_replace('\\', '/', $info->getSaveName());
        if ($this->postData['uptype'] == 2) {
            $this->modelDb->where('id', $this->uinfo['id'])->update(['thumb' => '/upload/' . $getSaveName]);
        }
        if ($info) {
            // return $this->app_success(['fileurl' => APP_URL.'/upload/'.$info->getSaveName()]);
            return $this->app_success(['fileurl' => '/upload/' . $getSaveName]);
        } else {
            // 上传失败获取错误信息
            return $this->app_error($file->getError());
        }
    }

    //上传附件
    public function upload_acce(Request $request)
    {
        // 获取表单上传文件
        $file = $request->file('Filedata');
        if (empty($file)) {
            return $this->app_error("请选择上传文件");
        }
        // trace($file);
        // 移动到框架应用根目录/public/uploads/ 目录下
        $info = $file->validate(['size' => 1024 * 1024 * 1024, 'ext' => 'jpg,png,gif,mp4,jpeg'])->move(ROOT_PATH . 'upload' . DS);
        if (empty($info)) {
            // 上传失败获取错误信息
            return $this->app_error($file->getError());
        }
        $getSaveName = str_replace('\\', '/', $info->getSaveName());
        $data['fileurl'] = "/upload/" . $info->getSaveName();
        $id = $this->modelDb->save_data($data);
        if ($id) {
            return $this->app_success(['id' => $id, 'url' => $data['fileurl']]);
        } else {
            return $this->app_error($this->modelDb->getError());
        }
    }
}